package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.wemedia.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * @author 陈辉
 * @data 2024 14:26
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinIOTemplate minIOTemplate;

    /**
     * 查询素材列表
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult pageQuery(WmMaterialDto wmMaterialDto) {
        //1. 参数校验
        if (wmMaterialDto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        wmMaterialDto.checkParam();

        //2. 组装查询条件：wrapper
        //2.1 条件1：是否收藏
        //2.2 条件2：按创建时间倒序排列
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(wmMaterialDto.getIsCollection() == 1, WmMaterial::getIsCollection, wmMaterialDto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime);


        //3. 构建分页Page
        Page page = new Page(wmMaterialDto.getPage(),wmMaterialDto.getSize());

        //4. 开启查询
        page(page,wrapper);             // select * from wm_materia where is_collection = ? order by created_time desc  limit ? , ?

        //5. 组装结果返回： total  list
        PageResponseResult pr = new PageResponseResult((int)page.getCurrent(),
                (int)page.getSize(),(int)page.getTotal());
        pr.setData(page.getRecords());

        return pr;
    }

    /**
     * 上传素材
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        try {
            //1.将文件上传到minio
            String originalFilename = multipartFile.getOriginalFilename();   // a.b.png
            //1.1 处理一下目标文件名，确保唯一性
            String uuid = UUID.randomUUID().toString();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = uuid + suffix;
            String url = minIOTemplate.uploadImgFile("", filename, multipartFile.getInputStream());

            //2. 将minio返回的图片路径封装成wm_material素材对象
            WmMaterial material = new WmMaterial();
            //2.1. 填充：url
            material.setUrl(url);
            //2.2. 填充：user_id  应该从ThreadLocal中动态获取当前登录用户id
            Integer userId = WmThreadLocalUtil.get();
            material.setUserId(userId);
            //2.3. 填充：is_collection(默认0，不收藏)
            material.setIsCollection((short)0);
            //2.4. 填充：created_time
            material.setCreatedTime(new Date());

            //3. 保存对象到数据库
            save(material);

            //4. 将url返回给前端用作数据回显
            return ResponseResult.okResult(material);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

    }
}
